﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using Website.Logger;
using DAL;
using BOL;
using WebLib;
using System.Web.Script.Services;
using System.Web.Services;
using System.IO;
using AjaxControlToolkit;
using UtilityExtensions;

namespace UILGestion.Admin.Empresas
{
    public partial class EmpresaEditForm : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                try
                {

                    internalid.Value = Request.Params["id"];
                    menuCtrl1.loadMenuSeguridad();
                    FormatForm();

                }
                catch (SqlException sqlex)
                {
                    WebServerSideSqlError.Log(sqlex);

                    ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                     "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


                }
                catch (Exception ex)
                {
                    WebServerSideError.Log(ex);
                    ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                         "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

                }

            }
        }
        protected void btnContinue_OnClick(object sender, EventArgs e)
        {
            saveButton.Enabled = false;
            try
            {

                if ((sender as Button).Text == "Guardar")
                {

                    EmpresaBL empresaBL = new EmpresaBL();

                    Empresa empresa = PopulateObject();
                    bool resultado=empresaBL.update(empresa);
                    if (resultado)
                                        Response.Redirect("EmpresaReadForm.aspx?id=" + internalid.Value, true);
                }
                if ((sender as Button).Text == "Cancelar")
                {
                    Response.Redirect("EmpresaListForm.aspx");
                }
                if ((sender as Button).Text == "refreshButton")
                {
                    FormatForm();
                }


            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);

                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                     "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }




        }
        private void ShowAllComboBox()
        {
            //dbGestionDataContext _db = new dbGestionDataContext(Parametros.strConnString);
            //var q = from i in _db.FormaPago
            //        select i;


            //formaPagoDropDownList.DataTextField = "descripcion";
            //formaPagoDropDownList.DataValueField = "idInternal";

            //formaPagoDropDownList.DataSource = q;
            //formaPagoDropDownList.DataBind();


        }

        private Empresa PopulateObject()
        {
            //(DD/MM/yyyy)
            System.IFormatProvider MiFp =
                new System.Globalization.CultureInfo("es-ES", false);


            Empresa entity = new Empresa();

            entity.idInternal=int.Parse(internalid.Value);
            entity.descripcion = presupuestoTextBox.Text;
            entity.direccion= direccionTextBox.Text;
            entity.activo = ActivoCheckBox.Checked;
            entity.ruc = rucTextBox.Text;
            entity.razonSocial = razonSocialTextBox.Text;
            entity.usuarioMod =(int) Session["idEmpleado"];
            entity.Logo = FirmaLabel.Text;
            
            //int idpadre = 0;
            //  int.TryParse(idPadreTextBox.Text.ToString(),out   idpadre);
            return entity;
        }
       
        private void editObject()
        {
            dbGestionDataContext _db = new dbGestionDataContext(Parametros.strConnString);
            Empresa empresa= _db.Empresas.Single(p => p.idInternal == int.Parse(internalid.Value));

            codigoLabel.Text = empresa.codigo;
            presupuestoTextBox.Text = empresa.descripcion;
            direccionTextBox.Text = empresa.direccion.ToString();
            rucTextBox.Text = empresa.ruc;
            razonSocialTextBox.Text = empresa.razonSocial;
            ActivoCheckBox.Checked = empresa.activo.Value;



        }
        private void FormatForm()
        {

            ShowAllComboBox();
            editObject();




        }

        protected void ExaminarFileUpload_UploadedComplete(object sender, EventArgs e)
        {
            //  System.Threading.Thread.Sleep(5000);

            if (ExaminarFileUpload.HasFile)
            {

                // 1. Save logic

                //string directorio = AppDomain.CurrentDomain.RelativeSearchPath;

                // dentro del directorio bin
                //string directorio = String.Format("\\\\192.168.1.116\\ObraPresupuesto\\{0}\\", idObra.Value);

                string rutaFirma = System.Web.HttpContext.Current.Server.MapPath("../App_Data/Empresa/Logo/");

                FirmaLabel.Text = ExaminarFileUpload.FileName;

                if (!Directory.Exists(rutaFirma))
                    Directory.CreateDirectory(rutaFirma);

                

                ExaminarFileUpload.SaveAs(rutaFirma + Path.GetFileName(ExaminarFileUpload.FileName));
                lblStatus.Text = "Archivo :" + ExaminarFileUpload.FileName + " Agregado";
                //ExaminarUpdatePanel.Update();

            }

        }

    }
}